﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Models
{    
    public class MsSqlStudentRepository : IStudentRepository
    {
        private readonly ApplicationDbContext dbContext;

        public MsSqlStudentRepository(ApplicationDbContext context)
        {
            dbContext = context;
        }

        public Student Create(Student student)
        {
            dbContext.Students.Add(student);
            dbContext.SaveChanges();
            return student;
        }

        public Student Delete(int id)
        {
            if (id <= 3) {
                throw new Exception("不允许删除！");
            }
            else {
                var s = dbContext.Students.Find(id);
                if (s != null) {
                    dbContext.Students.Remove(s);
                    dbContext.SaveChanges();
                }
                return s;
            }
        }

        public IEnumerable<Student> GetAllStudents()
        {
            return dbContext.Students;
        }

        public Student GetStudent(int id)
        {
            return dbContext.Students.Find(id);
        }

        public Student Update(Student student)
        {
            var s = dbContext.Students.Attach(student);
            s.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            dbContext.SaveChanges();

            return student;
        }
    }
}
